import { HttpClient, WsClient } from "tsrpc-browser"
import { Singleton } from "../framework/base/Singleton"
import { serviceProto, ServiceType } from "../src/shared/protocols/serviceProto"
import { Logger } from "../framework/Logger"
import { LayerManager } from "../framework/LayerManager"

/** 配置表管理 */
export class NetManager extends Singleton {

    public static get Ins() {
        return this.GetInstance<NetManager>()
    }

    private _http: HttpClient<ServiceType>
    private _socket: WsClient<ServiceType>

    get http() {
        if (!this._http) {
            this._http = new HttpClient(serviceProto, {
                server: "http://192.168.130.51:3000",
                // Remove this to use binary mode (remove from the server too)
                json: true,
                logger: console,
            });

        }
        return this._http
    }

    get socket() {
        return this._socket
    }

    async init() {
        this._socket = new WsClient(serviceProto, {
            server: "ws://192.168.130.51:3000",
            // Remove this to use binary mode (remove from the server too)
            json: true,
            // logger: console,
        })


        let f = () => { LayerManager.Ins.toast('连接超时') }
        setTimeout(() => { if (f) f() }, 5000);

        await this._socket.connect().then(({ isSucc, errMsg }) => {
            if (isSucc) {
                Logger.logNet('socket 连接成功')
                f = null
            } else {
                Logger.logNet('socket 连接失败：', errMsg)
            }
        })

        this._socket.flows.postDisconnectFlow.push(v => {
            Logger.logNet('socket 断开连接')
            this._socket = null
            return v
        })
    }


}